package com.miaomiao.controller.system;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.miaomiao.common.RedisPrefix;
import com.miaomiao.common.Result;
import com.miaomiao.domain.system.Icon;
import com.miaomiao.domain.system.Menu;
import com.miaomiao.domain.system.Router;
import com.miaomiao.mapper.system.IconMapper;
import com.miaomiao.service.system.MenuService;
import com.miaomiao.utils.JwtUtil;
import com.miaomiao.utils.RedisCache;
import com.miaomiao.utils.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/menu")
@Api(tags = "菜单管理")
public class MenuController {

    @Autowired
    MenuService menuService;

    @Autowired
    IconMapper iconMapper;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private JwtUtil jwtUtil;

    @GetMapping("/list")
    @PreAuthorize("@ss.hasPermis('system:menu')")
    @ApiOperation("获取菜单列表")
    public Result getMenuList(Menu menu){
        List<Menu> menuList = menuService.selectMenuTreeByUserId(menu,SecurityUtils.getUserId());
        return Result.success(menuList);
    }

    @GetMapping("/{menuId}")
    @PreAuthorize("@ss.hasPermis('system:menu')")
    @ApiOperation("获取菜单详细信息")
    public Result getMenu(@PathVariable Long menuId){
        LambdaQueryWrapper<Menu> queryWrapper = new LambdaQueryWrapper<Menu>();
        queryWrapper.eq(Menu::getMenuId, menuId);
        Menu menu = menuService.getOne(queryWrapper);
        return Result.success(menu);
    }

    @PostMapping
    @PreAuthorize("@ss.hasPermis('system:menu')")
    @ApiOperation("新增菜单")
    public Result addMenu(@RequestBody Menu menu){
        boolean save = menuService.addMenu(menu);
        if(save){
            redisCache.deleteObject("menuList");//删除缓存
            return Result.success("添加成功");
        }
        return Result.error("添加失败");
    }

    @PutMapping
    @PreAuthorize("@ss.hasPermis('system:menu')")
    @ApiOperation("修改菜单")
    public Result updateMenu(@RequestBody Menu menu){
        LambdaQueryWrapper<Menu> queryWrapper = new LambdaQueryWrapper<Menu>();
        queryWrapper.eq(Menu::getMenuId, menu.getMenuId());
        menu.setMenuId(null);
        boolean update = menuService.update(menu, queryWrapper);
        if(update){
            redisCache.deleteObject(RedisPrefix.ROUTERS_PRE + SecurityUtils.getUserId());
            return Result.success("修改成功");
        }
        return Result.error("修改失败");
    }

    @DeleteMapping("/{menuId}")
    @PreAuthorize("@ss.hasPermis('system:menu')")
    @ApiOperation("删除菜单")
    public Result DeleteMenu(@PathVariable String menuId){
        LambdaQueryWrapper<Menu> queryWrapper = new LambdaQueryWrapper<Menu>();
        queryWrapper.eq(Menu::getParentId, menuId);
        int count = menuService.count(queryWrapper);
        boolean remove = false;
        if(count == 0){
            queryWrapper.clear();
            queryWrapper.eq(Menu::getMenuId, menuId);
            remove = menuService.remove(queryWrapper);
        }else{
            return Result.error("请先删除子菜单");
        }
        if(remove){
            redisCache.deleteObject(RedisPrefix.ROUTERS_PRE + SecurityUtils.getUserId());
            return Result.success("删除成功");
        }
        return Result.error("删除失败");
    }

    @GetMapping("/treeselect")
    @PreAuthorize("@ss.hasPermis('system:menu')")
    @ApiOperation("菜单下拉树")
    public Result getMenuTree(){
        List<Menu> menuList = menuService.selectMenuTreeByUserId(SecurityUtils.getUserId());
        return Result.success(menuService.buildMenuTreeSelect(menuList));
    }

    @GetMapping("/icons")
    @PreAuthorize("@ss.hasPermis('system:menu')")
    @ApiOperation("获取所有图标")
    public Result getIcons(){
        List<Icon> icons = iconMapper.selectList(new QueryWrapper<>());
        return Result.success(icons);
    }

    @GetMapping("/getRouters")
//    @PreAuthorize("@ss.hasPermis('system:home')")
    @ApiOperation("获取用户动态路由")
    public Result getRouters(){
        List<Router> routers = null;
        Long userId = SecurityUtils.getUserId();
        routers = redisCache.getCacheObject(RedisPrefix.ROUTERS_PRE + userId);
        if(Objects.isNull(routers)){
            List<Menu> menus = menuService.selectMenuTreeByUserId(userId);
            routers = menuService.buildMenus(menus);
            redisCache.setCacheObject(RedisPrefix.ROUTERS_PRE + userId,routers,jwtUtil.getExpiration(), TimeUnit.MINUTES);
        }
        return Result.success(routers);
    }
}
